import React from 'react'
import { PlusOutlined, MinusCircleOutlined } from '@ant-design/icons';
import { Form, Input, Button } from 'antd'

const Demo = () => {
  const onFinish = values => {
    console.log('收到表单值：', values)
  }

  const rules = [
    { required: true, message: '必填' },
    {
      validator: async (_, names) => {
        console.info(_)
        if (!names || names.length < 2) {
          return Promise.reject(new Error('至少两名乘客'))
        }
      }
    },
    ({ getFieldValue }) => ({
      validator(_, value) {
        console.info('getFieldValue', getFieldValue(['names']))
        if (!value || getFieldValue('password') === value) {
          return Promise.resolve()
        }
        return Promise.reject(new Error('您输入的两个密码不匹配！'))
      }
    })
  ]

  return (
    <Form name="dynamic_form_nest_item" onFinish={onFinish} autoComplete="off">
      <Form.List
        name="users"
        // TODO: antd4 Form.List 仅支持自定义规则
        // rules={rules}
      >
        {(fields, { add, remove }) => (
          <>
            {fields.map(({ key, name, fieldKey, ...restField }) => (
              <div key={key} style={{ display: 'flex', marginBottom: 8, alignItems: 'baseline', gap: 8 }}>
                <Form.Item
                  {...restField}
                  name={[name, 'first']}
                  fieldKey={[fieldKey, 'first']}
                  rules={[{ required: true, message: '缺少名字' }]}
                >
                  <Input placeholder="名字" />
                </Form.Item>
                <Form.Item
                  {...restField}
                  name={[name, 'last']}
                  fieldKey={[fieldKey, 'last']}
                  rules={[{ required: true, message: '缺少姓氏' }]}
                >
                  <Input placeholder="姓氏" />
                </Form.Item>
                <MinusCircleOutlined onClick={() => remove(name)} />
              </div>
            ))}
            <Form.Item>
              <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined type="plus" />}>
                添加字段
              </Button>
            </Form.Item>
          </>
        )}
      </Form.List>
      <Form.Item>
        <Button type="primary" htmlType="submit">
          提交
        </Button>
      </Form.Item>
    </Form>
  )
}

export default Demo
